﻿using ASmile.Extend;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ASmile.Helpers
{
    public abstract class HttpEasyToken
    {
        static bool IsRunRefreshTask { set; get; }

        protected abstract string GetToken();
        /// <summary>
        /// 最后一个token值，切换用户时，先返回一个只有登陆权限的token，选择角色之后再替换，切换取消则恢复
        /// </summary>
        string LastToken { get; set; }
        /// <summary>
        /// 刷新token间隔事件(分钟)
        /// </summary>
        public int RefreshTokenMinutes { set; get; } = 2;
        /// <summary>
        /// 获取token值，
        /// </summary>
        public string TokenValue { get; private set; }

        protected virtual void PrintLog(string log, Exception ex = null)
        { }

        /// <summary>
        /// 刷新Token任务方法
        /// </summary>
        void RefreshTask()
        {
            if (IsRunRefreshTask)
            {
                LogHelper.LogObj.Error($"注意：程序多次执行刷新Token任务线程！！！");                
                return;
            }
            IsRunRefreshTask = true;
            while (true)
            {
                Thread.Sleep(TimeSpan.FromMinutes(RefreshTokenMinutes));
                try
                {
                    if (TokenValue.IsEmpty()) continue;

                    var newToken = GetToken();
                    if (newToken.IsEmpty()) continue;
                    if (!newToken.StringEquals(TokenValue))
                    {
                        SetToken(newToken);
                        PrintLog("Token 更新了");
                    }
                }
                catch (Exception ex)
                {
                    PrintLog("自动刷新token时发生异常", ex);
                }
            }
            //LogHelper.LogObj.Error($"注意：线程莫名其妙会终止！！！");
        }
        /// <summary>
        /// 设置Token
        /// </summary>
        public void SetToken(string token)
        {
            LastToken = TokenValue;
            TokenValue = token;
        }
        /// <summary>
        /// 恢复到上次的token
        /// </summary>
        public bool ResetToken()
        {
            if (LastToken.IsEmpty()) return false;
            TokenValue = LastToken;
            return true;
        }
        /// <summary>
        /// 开始刷新Token 任务
        /// </summary>
        public void Start()
        {
            Task.Factory.StartNew(RefreshTask, TaskCreationOptions.LongRunning);
        }
    }
}